package com.longlong.utils;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
/*
* 微信接入认证
*/

public class AccessAuthentincation implements Serializable {

    private String token;
    private String timestamp;
    private String nonce;
    private String signature;

    public AccessAuthentincation(String token, String timestamp, String nonce, String signature) {
        this.token = token;
        this.timestamp = timestamp;
        this.nonce = nonce;
        this.signature = signature;
    }

    public static AccessAuthentincation of(String token, String timestamp, String nonce, String signature){
        return new AccessAuthentincation(token,timestamp,nonce,signature);
    }

    /*验证接入*/
    public boolean checkSignature() throws Exception {
        // 1）将token、timestamp、nonce三个参数进行字典序排序
        String[] strings = new String[]{this.token,this.timestamp,this.nonce};
        Arrays.sort(strings);
        String str = strings[0]+strings[1]+strings[2];
        //2）将三个参数字符串拼接成一个字符串进行sha1加密
        String strSha1 = getSha1(str);
        //3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        return strSha1.equals(this.signature);
    }

    //sha1加密
    public static String getSha1(String str) throws Exception {
        if (null == str || 0 == str.length()) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }



}
